package cn.nange.cmfz.realm;

import cn.nange.cmfz.entity.Admin;
import cn.nange.cmfz.service.AdminService;
import cn.nange.cmfz.service.RoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class AuthorRealm extends AuthorizingRealm {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//        1.获取用户名 getPrimaryPrincipal(主身份信息)
        String username = (String) principals.getPrimaryPrincipal();
        System.out.println(username);
//        2.根据用户名获取角色信息和权限信息
        Set<String> roles = roleService.getAllRolesByUsername(username);
        Set<String> permissions = roleService.getAllPermissionsByUsername(username);

//        3.封装info
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken passwordToken = (UsernamePasswordToken) authenticationToken;
        String username = passwordToken.getUsername();

        Admin login = adminService.login(username);

        if (login != null){
            System.out.println("校验成功！");
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(login.getName(),
                    login.getPwd(), this.getName());
            return simpleAuthenticationInfo;
        }
        return null;
    }
}
